package com.godyao.mall.oauth.server.config;

import com.godyao.mall.oauth.server.exception.OAuthServerAuthenticationEntryPoint;
import com.godyao.mall.oauth.server.exception.OAuthServerClientCredentialsTokenEndpointFilter;
import com.godyao.mall.oauth.server.exception.OAuthServerWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;

/**
 * 认证中心的两个条件
 * 1.继承AuthorizationServerConfigurerAdapter
 * 2.@EnableAuthorizationServer注解标识
 * @author godyao
 * @date 2022/4/1
 */
@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private DataSource dataSource;

    /**
     * 继承WebSecurityConfigurerAdapter 在SecurityConfig中配置
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private OAuthServerAuthenticationEntryPoint authenticationEntryPoint;

    /**
     * 客户端存储策略，这里使用内存方式，后续可以存储在数据库
     */
    @Autowired
    private ClientDetailsService clientDetailsService;

    /**
     * 客户端信息配置
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 从数据源加载客户端信息
        clients.withClientDetails(new JdbcClientDetailsService(dataSource));
        // 从内存加载
        //clients.inMemory()
        //        //客户端id
        //        .withClient("myjszl")
        //        //客户端秘钥
        //        .secret(new BCryptPasswordEncoder().encode("123"))
        //        //资源id，唯一，比如订单服务作为一个资源,可以设置多个
        //        .resourceIds("res1")
        //        //授权模式，总共四种，1. authorization_code（授权码模式）、password（密码模式）、client_credentials（客户端模式）、implicit（简化模式）
        //        //refresh_token并不是授权模式，
        //        .authorizedGrantTypes("authorization_code","password","client_credentials","implicit","refresh_token")
        //        //允许的授权范围，客户端的权限，这里的all只是一种标识，可以自定义，为了后续的资源服务进行权限控制
        //        .scopes("all")
        //        //false 则跳转到授权页面
        //        .autoApprove(false)
        //        //授权码模式的回调地址
        //        .redirectUris("http://www.baidu.com");
    }

    /**
     * 授权码模式的service，使用授权码模式authorization_code必须注入
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        // 选择从数据源加载 也可以选择从内存加载
        //return new InMemoryAuthorizationCodeServices();
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    /**
     * 令牌管理服务配置
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        final DefaultTokenServices services = new DefaultTokenServices();
        // 客户端配置策略
        services.setClientDetailsService(clientDetailsService);
        // 支持令牌的刷新
        services.setSupportRefreshToken(true);
        // 令牌服务
        services.setTokenStore(tokenStore);
        //access_token的过期时间 7天
        services.setAccessTokenValiditySeconds(60 * 60 * 24 * 7);
        //refresh_token的过期时间 8天
        services.setRefreshTokenValiditySeconds(60 * 60 * 24 * 8);
        // 设置令牌增强
        services.setTokenEnhancer(jwtAccessTokenConverter);
        return services;
    }

    /**
     * 配置令牌访问的端点
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                // 处理用户名密码错授权类型不正确等异常  自定义返回
                .exceptionTranslator(new OAuthServerWebResponseExceptionTranslator())
                // 授权码模式所需要的authorizationCodeServices
                .authorizationCodeServices(authorizationCodeServices())
                // 密码模式需要的认证管理器
                .authenticationManager(authenticationManager)
                // 令牌管理服务，所有模式都需要设置
                .tokenServices(tokenServices())
                // 该端点只允许POST请求
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    /**
     * 设置令牌访问的安全约束
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        // 自定义ClientCredentialsTokenEndpointFilter，用户客户端id，密码错误等异常
        final OAuthServerClientCredentialsTokenEndpointFilter endpointFilter = new OAuthServerClientCredentialsTokenEndpointFilter(security, authenticationEntryPoint);
        endpointFilter.afterPropertiesSet();
        security.addTokenEndpointAuthenticationFilter(endpointFilter);

        security
                .authenticationEntryPoint(authenticationEntryPoint)
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()");
    }
}
